package com.izhengyin.demo.concurrent.basic;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author zhengyin
 * Created on 2021/11/29
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
        int threadNum = 2;


        final CyclicBarrier barrier = new CyclicBarrier(threadNum, new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " 完成最后任务");
            }
        });
        Random random = new Random();
        for(int i = 0; i < threadNum; i++) {
            new Thread(new ThreadGroup("worker"),() -> {
                try {
                    if(random.nextBoolean() || random.nextBoolean()){
                        System.out.println(Thread.currentThread().getThreadGroup().getName()+"#"+Thread.currentThread().getName()+" , barrier awaiting ");
                        barrier.await();
                        System.out.println(Thread.currentThread().getThreadGroup().getName()+"#"+Thread.currentThread().getName()+" , barrier await finish ");
                    }
                }catch (InterruptedException | BrokenBarrierException e){
                    e.printStackTrace();
                }
            }).start();
        }
    }

}